#include "notification.h"
#include "notifications-mover.h"


NotificationsMover::NotificationsMover (const int& height, const QList<Notification*>& notifications, QObject* parent)
    : QThread(parent), shiftHeight(height), notifications(notifications), shiftValue(3), waitValue(15)
{
    moveToThread(this);
}


void NotificationsMover::run()
{
    beginMovingWidgets();
    exec();
}


void NotificationsMover::beginMovingWidgets()
{
    moveTimer = new QTimer(this);
    connect (moveTimer.data(), &QTimer::timeout, this, &NotificationsMover::moveWidgets);
    moveTimer.data()->setSingleShot(true);

    if (shiftHeight % shiftValue == 0)
        moveTimer.data()->start(0);
    else
    {
        int firstShiftValue = shiftHeight % shiftValue;
        for (int i = notifications.size() - 1; i != 0; i--)
        {
            Notification* notification = notifications.at(i);
            connect (this, &NotificationsMover::move, notification, &Notification::moveRequest);
            emit move(notification->geometry().x(), notification->geometry().y() + firstShiftValue);
            disconnect (this, &NotificationsMover::move, notification, &Notification::moveRequest);
        }

        shiftHeight -= firstShiftValue;
    }
}


void NotificationsMover::moveWidgets()
{
    for (int i = notifications.size() - 1; i != 0; i--)
    {
        Notification* notification = notifications.at(i);
        connect (this, &NotificationsMover::move, notification, &Notification::moveRequest);
        emit move(notification->geometry().x(), notification->geometry().y() + shiftValue);
        disconnect (this, &NotificationsMover::move, notification, &Notification::moveRequest);
    }

    shiftHeight -= shiftValue;
}


void NotificationsMover::widgetMoved()
{
    if (shiftHeight != 0)
        moveTimer.data()->start(waitValue);
    else
    {
        delete moveTimer.data();
        quit();
    }
}


void NotificationsMover::quitRequest()
{
    delete moveTimer.data();
    quit();
}
